package com.zhongxiangspace.filter;

import com.google.gson.Gson;
import com.zhongxiangspace.entity.UserInfo;
import com.zhongxiangspace.result.NormalResult;
import com.zhongxiangspace.result.Result;
import freemarker.template.utility.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.AdviceFilter;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShiroLoginFilter extends AdviceFilter {
    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        UserInfo sysUser = (UserInfo) httpServletRequest.getSession().getAttribute("username");
        if (null == sysUser && !StringUtils.contains(httpServletRequest.getRequestURI(), "/memberLoin.do")) {
            System.out.println("a");
            String requestedWith = httpServletRequest.getHeader("X-Requested-With");
            if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals(requestedWith, "XMLHttpRequest")) {// 如果是ajax返回指定数据
                System.out.println(requestedWith);
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                String gson = new Gson().toJson(new NormalResult(5));
                httpServletResponse.getWriter().print(gson);
                return false;
            } else {// 不是ajax
                return true;
            }
        }
        return true;
    }


    public static boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
